/*
 * dbg.c
 *
 *  Created on: 2012-05-31
 *      Author: milgo
 */

#include "dbg.h"

char dbg_buf[DEBUG_BUF_LEN];
int dbg_buf_pos = 0;
char conv_buf[CONV_BUF_LEN];

void _clear_print_buf(void){
	dbg_buf[0] = '\0';
	dbg_buf_pos = 0;
}

void _writeln_println_buf(char* str, int len){
	int i=0;
	if(dbg_buf_pos + len + 2 > DEBUG_BUF_LEN)
	{
		//len = DEBUG_BUF_LEN - dbg_buf_pos - 2;
		_flush_print_buf();
		_clear_print_buf();
	}
	
	for(i=0;i<len&&str[i];i++)
		dbg_buf[dbg_buf_pos+i]=str[i];

	dbg_buf[dbg_buf_pos+i]='\n';
	i++;
	dbg_buf_pos += i;
	dbg_buf[dbg_buf_pos]=0;
}

void _flush_print_buf(void){
	printf("%s", dbg_buf);
	//printf("%s", itoa(dbg_buf_pos));
}

char* itoa(int i)
{
   char* ptr = conv_buf+CONV_BUF_LEN-1;
   char sign = 0;
   *ptr-- = 0;
   if (i < 0)
   {
      sign = 1;
      i = -i;
   }
   do
   {
      *ptr-- = 48 + (i % 10);
      i /= 10;
   }
   while (i > 0);
   if (sign == 1) *ptr-- = '-';
   return ++ptr;
}

char* ftoa(float f)
{
	int d1 = f, d2;           // Get the integer part (678).
	float f2 = f - d1;        // Get fractional part (678.0123 - 678 = 0.0123).
	d2 = trunc(f2 * 10000);   // Turn into integer (123).
	sprintf (dbg_buf, "%d.%04d", d1, d2);
	return dbg_buf;
}
